package io.sage.modules.employer.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.plugins.Page;

import io.sage.common.exception.RRException;
import io.sage.common.utils.PageUtils;
import io.sage.common.validator.Assert;
import io.sage.entity.TokenEntity;
import io.sage.form.LoginFormVo;
import io.sage.modules.employer.dao.EmployerMapper;
import io.sage.modules.employer.entity.Employer;
import io.sage.modules.employer.entity.StudentManager;
import io.sage.modules.employer.entity.StudentManagerExample;
import io.sage.modules.employer.service.EmployerService;
import io.sage.service.TokenService;


@Service("studentService")
public class EmployerServiceImpl implements EmployerService {
	@Autowired
	private EmployerMapper studentMapper;

	@Autowired
	private TokenService tokenService;
	
    @Value(value="${web.upload-headPortrait}")
    private String uploadHeadPortraitPath;

	@Value(value="${student.manager-time}")
	private String time;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        return new PageUtils(null);
    }

	@Override
	public PageUtils selectStudentList(Map<String, Object> params) {
		Integer limit = Integer.parseInt((String)params.get("limit"));
    	Integer pageNum = Integer.parseInt((String)params.get("page"));
		
		Page<Employer> page = new Page<>(pageNum,limit);
		page.setRecords(studentMapper.selectStudentList(page, params));
		
		return new PageUtils(page);
	}

	@Override
	public Employer selectByPrimaryKey(Integer id) {
		
		Employer student = studentMapper.selectByPrimaryKey(id);
		
		return student;
	}

	@Override
	public int insert(Employer record) {
		
		//如果获取不到值,就返回失败信息-1.
		Integer state=-1;
		/*SysUserEntity user = ShiroUtils.getUserEntity();
		if(!"".equals(user.getUserId())){
			//创建人.
			record.setUserId(user.getUserId().intValue());
		}else {
			return state;
		}
		if(!"".equals(user.getDeptId())){
			//设置部门id.
			record.setDeptId(user.getDeptId().intValue());
		}else {
			return state;
		}*/
		//创建日期.
		record.setCreateTime(new Date());
		//新增数据 数据状态(正常)设置为0.
		record.setDisFlag(0);
		
		//sha256加密
		/*String salt = RandomStringUtils.randomAlphanumeric(20);
		record.setSalt(salt);
		record.setUserPwd(ShiroUtils.sha256(record.getUserPwd(), record.getSalt()));*/
		
		state = studentMapper.insert(record);
		
		return state;
	}

	@Override
	public int updateByPrimaryKeySelective(Employer record) {
		if(StringUtils.isBlank(record.getUserPwd())){
			record.setUserPwd(null);
		}else{
//			record.setUserPwd(ShiroUtils.sha256(record.getUserPwd(), record.getSalt()));
		}
		int update = studentMapper.updateByPrimaryKeySelective(record);
		
		return update;
	}

	@Override
	public int deleteBatchIds(Integer[] ids) {
		
		int delete = studentMapper.deleteBatchIds(ids);
		
		return delete;
	}

	@Override
	public int insertByBatch(List<Employer> attachmentTables) {
		int insertByBatch = studentMapper.insertByBatch(attachmentTables);
		return insertByBatch;
	}

	@Override
	public List<String> getStudentList(Map<String, Object> params) {
		
		List<String> getStudentList = studentMapper.getStudentList(params);
		
		return getStudentList;
	}

	@Override
	public Employer selectByUserName(String userName) {
		
		Employer student = studentMapper.selectByUserName(userName);
		
		return student;
	}

	@Override
	public int updateBypwd(String userPwd, String newUserPwd, Employer student) {
		
		String pwd = DigestUtils.sha256Hex(userPwd);

		//输入的原密码
		String userPwd2 = student.getUserPwd();
		
		if(!userPwd2.equals(pwd)){
			return -1;
		}
		
		//sha256加密
		Employer sss=new Employer();
		sss.setId(student.getId());
		//新密码
		sss.setUserPwd(DigestUtils.sha256Hex(newUserPwd));
		
		return studentMapper.updateByPrimaryKeySelective(sss);
	}

	@Override
	public Map<String, Object> login(LoginFormVo form) {
		Map<String, Object> map = new HashMap<>(2);
		//如果用户名不为空,说明登录名称是使用用户名登录.
		if(StringUtils.isNotBlank(form.getUsername())){
		
			Employer employer = selectByUserName(form.getUsername());
			
			//如果对象为空.
			if(employer==null){
				map.put("code", 1);
//				return map;
				throw new RRException("用户或密码错误");
			}
			
			//先判断用户状态，是否被禁用.
			Integer disFlag = employer.getDisFlag();
			if(1==disFlag){
				throw new RRException("用户被禁用");
			}
			Assert.isNull(employer, "用户名或密码错误");
	
			//密码错误
			if(!employer.getUserPwd().equals(DigestUtils.sha256Hex(form.getPassword()))){
				throw new RRException("用户名或密码错误");
			}
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("employerId", employer.getId());
			/*String phone="";
			try{
				phone= GetOpenid.getUserInfo(form.getPhone(), form.getSessionKey(), form.getIv()).getString("phoneNumber");
			}catch (Exception e){
				throw new RRException("请勿在多台机器上重复登陆！！！");
			}*/

/*			StudentManager studentManager=this.getStudentManageByStuent(student);*/
			/*if(new Date().getTime()>studentManager.getStopTime().getTime()){
				throw new RRException("账号已过期，请联系管理员");
			}*/
			//获取登录token
			TokenEntity tokenEntity = tokenService.createToken(employer.getId());
			employer.setFrequency(0);

			map.put("token", tokenEntity.getToken());
			map.put("expire", tokenEntity.getExpireTime().getTime() - System.currentTimeMillis());
			map.put("userId", tokenEntity.getUserId());
			map.put("userInfo", employer);
			
			return map;
		
		}else if(StringUtils.isNotBlank(form.getPhone())){
			
			Employer student = selectByPhone(form.getPhone());
			//如果对象为空.
			if(student==null){
				map.put("code", "1");
				return map;
			}
			
			//先判断用户状态，是否被禁用.
			Integer disFlag = student.getDisFlag();
			if(1==disFlag){
				throw new RRException("用户被禁用");
			}
			
			Assert.isNull(student, "手机号或密码错误");
	
			//密码错误
			if(!student.getUserPwd().equals(DigestUtils.sha256Hex(form.getPassword()))){
				
				map.put("code", "1");
				map.put("msg", "手机号或密码错误");
				return map;
//				throw new RRException("手机号或密码错误");
			}
			StudentManager studentManager=this.getStudentManageByStuent(student);
			if(new Date().getTime()>studentManager.getStopTime().getTime()){
				throw new RRException("账号已过期，请联系管理员");
			}
			//获取登录token
			TokenEntity tokenEntity = tokenService.createToken(student.getId());
	
//			Map<String, Object> map = new HashMap<>(2);
			map.put("token", tokenEntity.getToken());
			map.put("expire", tokenEntity.getExpireTime().getTime() - System.currentTimeMillis());
			map.put("userId", tokenEntity.getUserId());
			
			return map;
			
		}else if (StringUtils.isNotBlank(form.getIdcards())) {
			Employer student = selectByIDCard(form.getIdcards());
			
			//如果对象为空.
			if(student==null){
				map.put("code", "1");
				return map;
			}
			
			//先判断用户状态，是否被禁用.
			Integer disFlag = student.getDisFlag();
			if(1==disFlag){
				throw new RRException("用户被禁用");
			}
			Assert.isNull(student, "身份证或密码错误");
	
			//密码错误
			if(!student.getUserPwd().equals(DigestUtils.sha256Hex(form.getPassword()))){
				throw new RRException("身份证或密码错误");
			}
			StudentManager studentManager=this.getStudentManageByStuent(student);
			if(new Date().getTime()>studentManager.getStopTime().getTime()){
				throw new RRException("账号已过期，请联系管理员");
			}
			//获取登录token
			TokenEntity tokenEntity = tokenService.createToken(student.getId());
	
//			Map<String, Object> map = new HashMap<>(2);
			map.put("token", tokenEntity.getToken());
			map.put("expire", tokenEntity.getExpireTime().getTime() - System.currentTimeMillis());
			map.put("userId", tokenEntity.getUserId());
			
			return map;
		}
		return null;
	}

	@Override
	public Employer selectByPhone(String phone) {
		return studentMapper.selectByPhone(phone);
	}

	@Override
	public Employer selectByIDCard(String IDCard) {
		
		return studentMapper.selectByIDCard(IDCard);
	}

	@Override
	public int updateBypwd(String userPwd, String newUserPwd, String resetPwd, Employer student) {
		//原始密码
		String pwd = DigestUtils.sha256Hex(userPwd);
		String newUserPwda = DigestUtils.sha256Hex(newUserPwd);
		
		//系统获取原始密码.
		String userPwd2 = student.getUserPwd();
		
		if(!userPwd2.equals(pwd)){
			return -1;
		}
		
		//sha256加密
		Employer sss=new Employer();
		sss.setId(student.getId());
		//新密码
		sss.setUserPwd(newUserPwda);
		
		return studentMapper.updateByPrimaryKeySelective(sss);
	}

    @Override
    @Transactional
    public String uploadHeadPortrait(Employer student, MultipartFile file) throws Exception {
        Integer id = student.getId();
        
        InputStream is = file.getInputStream();
        
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String filePath = uploadHeadPortraitPath + uuid + ".png";
        File headPortraitFile = new File(filePath);
        
        // 循环读取输入流文件内容，通过输出流将内容写入新文件
        OutputStream os = new FileOutputStream(headPortraitFile);  
        byte buffer[] = new byte[1024];  
        int cnt = 0;  
        while((cnt=is.read(buffer)) > 0) {  
            os.write(buffer, 0, cnt);  
        }  
        //关闭输入输出流
        os.close();
        is.close();
        
        // 修改文件url路径.
        Employer s = new Employer();
        s.setId(id);
        s.setUrl(filePath);
        studentMapper.updateByPrimaryKeySelective(s);
        
        return filePath;
    }

    public StudentManager getStudentManageByStuent(Employer student){
		StudentManagerExample studentManagerExample=new StudentManagerExample();
		StudentManagerExample.Criteria criteria=studentManagerExample.createCriteria();
		criteria.andUserNameEqualTo(student.getUserName());
		/*List<StudentManager> studentManagers=this.studentManagerMapper.selectByExample(studentManagerExample);
		StudentManager studentManager=new StudentManager();
		if(studentManagers.size()>0){
			studentManager=studentManagers.get(0);
		}else{
			studentManager.setCreateTime(student.getCreateTime());
			studentManager.setDeptId(student.getDeptId());
			studentManager.setDisFlag(student.getDisFlag());
			studentManager.setUserName(student.getUserName());
			studentManager.setUpdateTime(student.getUpdateTime());
			studentManager.setStopTime(DateUtils.addDateDays(student.getCreateTime(), Integer.parseInt(time)));
			this.studentManagerMapper.insertSelective(studentManager);
		}*/
		return null;
	}

}
